package logic

import (
	"context"
	"errors"
	"ns/app/applet/api/internal/code"
	"ns/app/applet/api/internal/model"
	"ns/pkg/xcrypt"
	"ns/pkg/xjwt"

	"ns/app/applet/api/internal/svc"
	"ns/app/applet/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
	// 查找用户
	user, err := l.svcCtx.UserModel.FindOneByMobile(l.ctx, req.Mobile)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, code.ErrMobileNotExists
		}
		return nil, err
	}
	// 验证密码是否正确
	if !xcrypt.ComparePassword(user.Password, req.Password) {
		return nil, code.ErrPasswordIncorrect
	}
	// 验证验证码
	verifyCode, err := l.svcCtx.UserModel.GetMessageVerifyCode(l.ctx, req.Mobile)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, code.ErrVerifyCodeIncorrect
		}
		return nil, err
	}
	if verifyCode != req.Code {
		return nil, code.ErrVerifyCodeIncorrect
	}

	// 加密手机号
	encMobile, err := xcrypt.EncryptAESWithECB(user.Mobile, l.svcCtx.Config.Aes.Key)
	if err != nil {
		return nil, err
	}

	// 生成token
	iat := xjwt.GetTimeNow()
	token, err := xjwt.GenToken(xjwt.TokenOptions{
		SecretKey: l.svcCtx.Config.Auth.AccessSecret,
		Payloads: xjwt.TokenData{
			UserId:    user.Id,
			UserType:  user.Type,
			UserLevel: int64(user.Level),
			Province:  user.Province,
			City:      user.City.String,
			Area:      user.Area.String,
			Mobile:    encMobile,
		},
		Iat:     iat,
		Seconds: l.svcCtx.Config.Auth.AccessExpire,
	})
	if err != nil {
		return nil, err
	}

	return &types.LoginResponse{
		Token: token,
	}, nil

}
